<template>
    <el-button type="primary"  @click="dialogVisible = true">批量上传</el-button> 
    <el-dialog v-model="dialogVisible" width="500px" :before-close="handleClose">
        <el-upload
            ref="uploadFile"
            drag
            action="#"
            :multiple="false"
            :limit="1"
            accept=".txt"
            :http-request="beforeAvatarUploadThree"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-exceed="uploadExceed">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传txt文件，且不超过10M，一次只能上传一个</div>
        </el-upload>
        <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
              </span>
            </template>
    </el-dialog> 
</template>
<script>
import _axios, { get, put, _delete } from '@/lin/plugin/axios'
import { reactive, ref, onMounted } from 'vue'
import {ElMessage } from 'element-plus'
import Config from '@/config/index'

export default {

    name: 'upload-text',

    props: {
        fileType: {
            type: String,
            default: '',
        },
    },
    
    data(){
        let textFile = ref(null)

        return {
            textFile,
            dialogVisible: false,
        };
    },
   
    methods: {

        beforeAvatarUploadThree() { 
            const uploadUrl =  Config.baseURL+'cms/file/text/'+this.fileType;

            let params = new FormData()
            params.append("file", this.textFile);
            _axios({
                method:'post',
                url:uploadUrl,
                data:params,
                headers:{
                    'content-type':'multipart/form-data'
                }
            }).then(res => {
                this.uploadSuccess(res)
            })
            .catch(err => {
                console.log(err)
            })
        },
        // 点击按钮手动上传，会先触发beforeUpload，再执行上传
        submit() {
           this.$refs.uploadFile.submit();
        },
 
        // 文件上传前对文件类型、文件大小判断限制
        beforeUpload(file) {
            this.textFile = file;
            const { name, size } = file;
            const index = name.lastIndexOf('.');
            // 判断文件名是否有后缀，没后缀文件错误
            if(index === -1) {
                this.$notify.error({
                    title: '错误',
                    message: '文件错误，请重新上传！',
                });
                return false;
            }
            const fileType = name.substr(index + 1);
            const acceptFileTypes = ['txt'];
            // 判断文件类型
            if(!acceptFileTypes.includes(fileType)) {
                this.$notify.error({
                    title: '错误',
                    message: '文件类型错误，请重新上传！',
                });
                return false;
            }
            // 判断文件大小
            if(size > 10*1024*1024) {
                this.$notify.error({
                    title: '错误',
                    message: '文件大小超过10M，请重新上传！',
                });
                return false;
            }
        
            // 默认true
            return true;
        },
 
        // 上传接口调取成功status为200
        uploadSuccess(res) {
            if(res.code === 31) {  // 文件上传成功
                ElMessage.success(`${res.message}`)
               this.dialogVisible = false;
            } else {
                this.uploadError(res);
            }
        },
 
        // 文件上传失败
        uploadError(res) {
            ElMessage.error(`${res.message}`)
        },
 
        // 文件个数超过限制
        uploadExceed() {
            this.$notify.warning({
                title:'提示',
                message: '您已添加了一个文件，如需替换，请先删除已添加的文件！',
            });
        },

        handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },

    

    }
}
</script>
<style scoped>

.btn-footer {
    margin-top: 10px;
}
</style>